//
//  EPCNewFeatureView.swift
//  Weibo
//
//  Created by LioWu on 11/04/2017.
//  Copyright © 2017 MyGit. All rights reserved.
//

import UIKit

private let pageCount = 4

class EPCNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var enterButton: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    class func newFeatureView() -> EPCNewFeatureView {
        
        let nib = UINib.init(nibName: "EPCNewFeatureView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! EPCNewFeatureView
        
        return v
    }
    
    override func awakeFromNib() {
        
        frame = UIScreen.main.bounds
        
        let width = UIScreen.main.bounds.width
        let height = UIScreen.main.bounds.height
        
        for i in 0..<pageCount {
            let img = UIImage.init(named: "new_feature_\(i+1)")
            let imgView = UIImageView.init(image: img)
            imgView.frame = CGRect.init(x: CGFloat(i) * width, y: 0, width: width, height: height)
            scrollView.addSubview(imgView)
        }
        
        scrollView.contentSize = CGSize.init(width: CGFloat(pageCount + 1) * bounds.width , height: height)
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        
        scrollView.delegate = self
        
        enterButton.isHidden = true
        
        pageControl.isEnabled = false
    }
    

    @IBAction func enterAction(_ sender: Any) {
        removeFromSuperview()
    }
    
}

// MARK: - UIScrollViewDelegate
extension EPCNewFeatureView:UIScrollViewDelegate {

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        let page = Int(scrollView.contentOffset.x/scrollView.bounds.width)
        
        if page == pageCount {
            removeFromSuperview()
        }
        
        if page < pageCount {
            pageControl.currentPage = page
        }
        
        enterButton.isHidden = (page != pageCount - 1)
        pageControl.isHidden = (page >= pageCount)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        enterButton.isHidden = true
    }
    
}
